import x2js from 'x2js'
import axios from 'axios'
// const sysConfig = require('@/config/sysConfig')
import {
  getToken,
  setToken
} from '@/utils/auth'
import store from '../store'
import router from '../router'
const casServerUrl = process.env.VUE_APP_CAS_BASE_URL || ''
const sysDomain = location.origin
const casLoginUrl = `${casServerUrl}/cas/login`
export default {

  enableCasAuth() {
    const token = getToken()
    if (token) {
      return
    }

    if (this.isCasCallback()) {
      const ticket = this.getTicket()
      this.getAuthInfo(ticket).then(res => {
        if (res.success) {
          const user_id = res.username.__text
          localStorage.setItem('name', user_id)
          this.login(user_id)
        } else {
          this.toAuth()
        }
      })
    } else {
      this.toAuth()
    }
  },
  toAuth() {
    location.href = `${casLoginUrl}?locale=zh_CN&service=${sysDomain}`
  },
  toIndex(path) {
    location.href = sysDomain + '/#/' + path
  },
  getTicket() {
    var reg = new RegExp('(^|&)ticket=([^&]*)(&|$)', 'i')
    var r = window.location.search.substr(1).match(reg)
    if (r != null) return unescape(r[2])
    return null
  },
  getAuthInfo(ticket) {
    return axios.get(`/cas/serviceValidate?locale=zh_CN&service=${sysDomain}&ticket=${ticket}`).then(res => {
      debugger
      const x2j = new x2js()
      var info = x2j.xml2js(res.data)
      if (info.serviceResponse.authenticationSuccess) {
        return {
          'success': true,
          'username': info.serviceResponse.authenticationSuccess.user
        }
      } else {
        return {
          'success': false,
          'username': ''
        }
      }
    })
  },
  isCasCallback() {
    const url = window.location.href
    return url.indexOf(sysDomain + '/?ticket=') != -1
  },
  logout() {
    location.href = `${casServerUrl}/cas/logout?locale=zh_CN&service=${sysDomain}`
  },
  getUserByUserId(user_id) {
    return axios.post(`/user/${user_id}`)
  },
  login(user_id) {

    store
      .dispatch('Code2User', user_id)
      .then(() => {
        router.push({ path: '/' }).catch(() => {})
      })
      .catch(() => {
        // this.loading = false
        // this.getCode()
      })
    // this.getUserByUserId(user_id)
    //   .then(async (response) => {
    //     const data = response.data
    //     if (data.code === 200) {

    //       setToken(data.token)
    //       var token = data.token
    //       axios.defaults.headers.common['token'] = getToken()
    //       store.commit('user/SET_TOKEN', token)
    //       // const {
    //       //   roles
    //       // } = await store.dispatch('user/getInfo')
    //       //为了方便，直接给予ADMIN权限
    //       let roles = ['ADMIN']
    //       const accessRoutes = store.dispatch('permission/generateRoutes', roles)
    //       router.addRoutes(accessRoutes)
    //     } else {
    //       router.push({
    //         path: '/401'
    //       })
    //     }
    //   })
  }
}
